﻿using BaseUI;
using BLL;
using System;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace Thksoft.BusinessExpansion.Print
{
    public partial class MainPrint : BasePage
    {
        protected override void OnPreInit(EventArgs e)
        {
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PrintKey = Request.QueryString["ID"];

                PrintValue = Request.QueryString["VALUE"];
                if (PrintKey == "HTML")
                {
                    PRINT_BODY.InnerHtml = "<table style='width:100%'>" + (string)Session[PrintValue] + "</table>";
                    return;
                }
                if (PrintKey == "")
                {
                    MessageBox.ShowAndRedirectClose(this, "请传入正确的打印参数Key");
                    return;
                }
            }
            BasePrint print = null;
            /*进入打印方法*/
            if (PrintKey == "BASIC")
            {
                print = new BasePrint(this);
            }

            if (print == null)
            {
                MessageBox.ShowAndRedirectClose(this, "没有找到打印方法");
            }
            else
            {
                print.BindGo();
            }
        }

        /// <summary>
        /// 打印Key
        /// </summary>
        public string PrintKey
        {
            get
            {
                return PRINT_KEY.Value;
            }
            set
            {
                PRINT_KEY.Value = value;
            }
        }

        /// <summary>
        /// 打印参数
        /// </summary>
        public string PrintValue
        {
            get
            {
                return PRINT_VALUE.Value;
            }
            set
            {
                PRINT_VALUE.Value = value;
            }
        }
    }

    public class BasePrint
    {
        public BasePrint(MainPrint page)
        {
            Page = page;
        }

        public MainPrint Page { get; set; }
        private string title { get; set; }
        private DataTable DataBase { get; set; }

        public virtual void BindGo()
        {
            if (!Page.IsPostBack)
            {
                //No.1渲染Header
                var herder = (string)Page.Session[Page.PrintValue + "Header"];
                if (herder == null)
                {
                    MessageBox.ShowAndRedirectClose(Page, "Header参数不能空");
                    return;
                }
                title = herder + "@" + Page.CurrentUserCompanyName;

                //No.2渲染Body
                var body = (DataTable)Page.Session[Page.PrintValue + "Body"];
                if (body == null)
                {
                    MessageBox.ShowAndRedirectClose(Page, "Body参数不能空");
                    return;
                }
                DataBase = body;
                /*
                var htmlBuilder = new StringBuilder();
                htmlBuilder.Append("<table class=\\\"BasicTable\\\">");
                //加载标题
                htmlBuilder.Append("<tr>");
                htmlBuilder.Append("<td align=\\\"center\\\"colspan=\\\"" + DataBase.Columns.Count + "\\\" style=\\\"font-size:20px;\\\">");
                htmlBuilder.Append(title);
                htmlBuilder.Append("</td>");
                htmlBuilder.Append("</tr>");
                //加载表头
                htmlBuilder.Append("<tr>");
                foreach (DataColumn item in DataBase.Columns)
                {
                    htmlBuilder.Append("<td>" + item.ColumnName + "</td>");
                }
                htmlBuilder.Append("</tr>");
                //加载数据
                foreach (DataRow item in DataBase.Rows)
                {
                    htmlBuilder.Append("<tr>");
                    foreach (DataColumn itm in DataBase.Columns)
                    {
                        htmlBuilder.Append("<td>" + item[itm.ColumnName].ToString() + "</td>");
                    }
                    htmlBuilder.Append("</tr>");
                }
                //加载页底
                htmlBuilder.Append("<tr>");
                htmlBuilder.Append("<td align=\\\"right\\\" colspan=\\\"" + DataBase.Columns.Count + "\\\">" + "制表人：" + Page.CurrentUserName + "、打印日期:" + DateTime.Now.ToString("yyyy年MM月dd日") + "</td>");
                htmlBuilder.Append("</tr>");
                htmlBuilder.Append("</table>");
                MessageBox.ResponseScript(Page, "$(\"#PRINT_BODY\").html(\"" + htmlBuilder .ToString()+ "\");");
                */
                DrawData();
            }
        }

        public void DrawData()
        {
            int allCount = DataBase.Rows.Count;
            ColumnNum = DataBase.Columns.Count;
            int pageCount = 30; //int.Parse(ConfigurationManager.AppSettings["HReportRow"].ToString()); ;//每一页显示的行数

            string companyName = Page.CurrentUserCompanyName;

            string nowdate = DateTime.Now.ToString("yyyy年MM月dd日");
            //下面4行分别声明要打印的表、表头、表体、表尾
            HtmlGenericControl ht = null;
            HtmlGenericControl myThead = null;
            HtmlGenericControl myTbody = null;
            HtmlGenericControl myTfoot = null;
            HtmlGenericControl myTable = null;

            HtmlTableRow row = null;
            HtmlTableCell cell = null;

            Table tb = new Table();
            tb.Width = Unit.Percentage(100);
            TableRow tr = new TableRow();
            TableCell td = new TableCell();
            td.VerticalAlign = VerticalAlign.Top;
            td.BorderStyle = BorderStyle.None;
            td.HorizontalAlign = HorizontalAlign.Center;
            myTable = CreateHTMLMainTable("95%", "border-collapse:collapse;border:2px;", string.Empty);
            myThead = new HtmlGenericControl("thead");
            myThead.Attributes.Add("style", "display:table-header-group;font-weight:bold");
            myTbody = new HtmlGenericControl("tbody");
            myTfoot = new HtmlGenericControl("tfoot");
            myTfoot.Attributes.Add("style", "display:table-footer-group;font-weight:bold");
            myTable.Controls.Add(myThead);
            myTable.Controls.Add(myTbody);
            myTable.Controls.Add(myTfoot);
            td.Controls.Add(myTable);
            tr.Controls.Add(td);
            tb.Controls.Add(tr);
            Page.PRINT_BODY.Controls.Add(tb);

            ht = CreateHTMLMainTable("100%", "border-top-width:0px", string.Empty);//创建一个Table作为表体

            ht = FillDataToHtmlHeadTable(companyName, nowdate);

            ht = FillDataToHtmlTable(DataBase, ht, "td_tableData");//插入数据行

            row = CreateHTMLRow("30px", null, "tr_pageHead");

            string userName = Page.CurrentUserName;
            row.Cells.Add(CreateHTMLCell("制表人：" + userName, "font-size:12pt", "left", null, (ColumnNum / 2)));

            row.Cells.Add(CreateHTMLCell("打印日期：" + nowdate, "font-size:12pt", "right", null, ((ColumnNum % 2) == 0 ? ColumnNum / 2 : ColumnNum / 2 + 1)));
            ht.Controls.Add(row);

            FillTableToTbody(ht, ref myTbody, allCount, pageCount, 0);
        }

        #region 添加数据

        /// <summary>
        /// 添加数据到表头
        /// </summary>
        /// <param name="dtHead"></param>
        /// <param name="projectType"></param>
        /// <param name="companyName"></param>
        /// <param name="currentPage"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private HtmlGenericControl FillDataToHtmlHeadTable(string companyName, string nowdate)
        {
            HtmlTableRow row = null;
            HtmlGenericControl ht = null;

            ht = CreateHTMLMainTable("100%", "border-bottom-width:0px", "");//td_table

            row = CreateHTMLRow("50px", null, "tr_pageHead");

            row.Cells.Add(CreateHTMLCell("<strong>" + title.Split('@')[0].ToString() + "</strong>", "font-size:20pt;width:100%", "center", null, ColumnNum));
            ht.Controls.Add(row);

            row = CreateHTMLRow(null, null, "tr_pageHead");
            ht.Controls.Add(row);
            if (title.Split('@')[1].ToString() != "none")
            {
                row = CreateHTMLRow(null, "border:0px solid; border-color:black;", "tr_pageHead");
                row.Cells.Add(CreateHTMLCell("编制单位：" + companyName, "font-size:12pt;border-color:black;", "left", null, (ColumnNum / 2)));
                row.Cells.Add(CreateHTMLCell("单位：" + title.Split('@')[1].ToString(), "font-size:12pt;border-color:black;", "right", null, ((ColumnNum % 2) == 0 ? ColumnNum / 2 : ColumnNum / 2 + 1)));
                ht.Controls.Add(row);
            }

            row = CreateHTMLRow("", null, "");

            for (int i = 0; i < DataBase.Columns.Count; i++)
            {
                row.Cells.Add(CreateHTMLCell("<strong>" + DataBase.Columns[i].ColumnName + "</strong>", "border-top-width:2px;border:1px solid;", "center", "td_tableData", 1));
            }

            ht.Controls.Add(row);

            return ht;
        }

        /// <summary>
        /// 添加数据到表格
        /// </summary>
        /// <param name="dtA"></param>
        /// <param name="ht"></param>
        /// <returns></returns>
        private HtmlGenericControl FillDataToHtmlTable(DataTable dtA, HtmlGenericControl ht, string dataCellClass)
        {
            HtmlTableRow row = null;
            foreach (DataRow dr in dtA.Rows)
            {
                row = CreateHTMLRow("", null, "");
                for (int i = 0; i < DataBase.Columns.Count; i++)
                {
                    row.Cells.Add(CreateHTMLCell(dr[i].ToString() == "" ? "&nbsp;" : dr[i].ToString(), "border-left-width:1px;border-top-width:0px;border:1px solid;", "center", dataCellClass, 1));
                }

                ht.Controls.Add(row);
            }
            return ht;
        }

        /// <summary>
        /// 添加空数据到表格
        /// </summary>
        /// <param name="rowCount"></param>
        /// <param name="table"></param>
        /// <param name="dataCellClass"></param>
        /// <returns></returns>
        private HtmlGenericControl FillEmptyDataToHtmlTable(int rowCount, HtmlGenericControl table, string dataCellClass)
        {
            HtmlTableRow row = null;

            for (int j = 0; j < rowCount; j++)
            {
                row = CreateHTMLRow("", null, null);
                //row.Cells.Add(CreateHTMLCell("&nbsp;", " border-left-width:2px;border-top-width:0px; ", "left", dataCellClass, 1));
                //row.Cells.Add(CreateHTMLCell("&nbsp;", " border-top-width:0px;  ", "left", dataCellClass, 1));
                //row.Cells.Add(CreateHTMLCell("&nbsp;", " border-top-width:0px;  ", "left", dataCellClass, 1));
                //row.Cells.Add(CreateHTMLCell("&nbsp;", " border-top-width:0px; ", "left", dataCellClass, 1));
                //row.Cells.Add(CreateHTMLCell("&nbsp;", " border-top-width:0px; ", "left", dataCellClass, 1));
                //row.Cells.Add(CreateHTMLCell("&nbsp;", " border-top-width:0px;border-right-width:2px; ", "left", dataCellClass, 1));

                table.Controls.Add(row);
            }
            return table;
        }

        /// 获取一页数据

        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="pageCount"></param>
        /// <param name="currentPage"></param>
        /// <returns></returns>
        private DataTable GetListDataOfOnePage(DataTable dataTable, int pageCount, int currentPage)
        {
            DataTable returnTable = dataTable.Clone();

            DataRow dr = null;
            int beginCount = (currentPage - 1) * pageCount;
            int endCount = dataTable.Rows.Count;
            for (int i = beginCount; i < endCount && i < currentPage * pageCount; i++)
            {
                dr = dataTable.Rows[i];
                returnTable.ImportRow(dr);
            }
            return returnTable;
        }

        private void FillTableToTbody(HtmlGenericControl table, ref HtmlGenericControl tBody, int allCount, int pageCount, int currentPage)
        {
            HtmlTableCell cell = null;
            HtmlTableRow row = null;
            cell = CreateHTMLCell(null, "width:100%", null, null, 12);
            cell.Controls.Add(table);

            row = CreateHTMLRow(null, null, null);
            row.Cells.Add(cell);
            tBody.Controls.Add(row);
            if (allCount > pageCount && allCount - pageCount * currentPage > 0)
            {
                row = CreateHTMLRow(null, "display:none;page-break-before:always", null);
                tBody.Controls.Add(row);
            }
        }

        protected int AccountValueLenth(string value)
        {
            int valueLenth;
            byte[] array = System.Text.Encoding.Default.GetBytes(value);
            return valueLenth = array.Length;
        }

        #endregion 添加数据

        private int ColumnNum = 0;

        #region 创建表格

        public HtmlTableCell CreateHTMLCell(string cellText, string cellStyle, string cellAlign, string cellClass, int cellCospan)
        {
            HtmlTableCell cell = new HtmlTableCell();
            return cell = CreateHTMLCell(cellText, cellStyle, cellAlign, cellClass, cellCospan, 1);
        }

        public HtmlTableCell CreateHTMLCell(string cellText, string cellStyle, string cellAlign, string cellClass, int cellCospan, int cellRowspan)
        {
            return CreateHTMLCell(cellText, cellStyle, cellAlign, null, cellClass, cellCospan, cellRowspan);
        }

        public HtmlTableCell CreateHTMLCell(string cellText, string cellStyle, string cellAlign, string cellValign, string cellClass, int cellCospan, int cellRowspan)
        {
            HtmlTableCell cell = new HtmlTableCell();
            if (cellText != null)
            {
                cell.InnerHtml = Page.Server.HtmlDecode(cellText);
            }
            if (cellStyle != null)
            {
                cell.Attributes.Add("style", cellStyle);
            }
            if (cellCospan > 1)
            {
                cell.ColSpan = cellCospan;
            }
            if (cellAlign != null)
            {
                cell.Align = cellAlign;
            }
            if (cellValign != null)
            {
                cell.VAlign = cellValign;
            }
            if (cellClass != null)
            {
                cell.Attributes.Add("class", cellClass);
            }
            if (cellRowspan > 1)
            {
                cell.RowSpan = cellRowspan;
            }
            return cell;
        }

        public HtmlTableRow CreateHTMLRow(string rowHeight, string rowStyle, string rowClass)
        {
            HtmlTableRow row = new HtmlTableRow();
            if (rowHeight != null)
            {
                row.Height = rowHeight;
            }
            if (rowStyle != null)
            {
                row.Attributes.Add("style", rowStyle);
            }
            if (rowClass != null)
            {
                row.Attributes.Add("class", rowClass);
            }
            return row;
        }

        public HtmlTable CreateHTMLTable(string width, string tableClass)
        {
            return CreateHTMLTable(width, string.Empty, tableClass, "0", "0", "0");
        }

        public HtmlTable CreateHTMLTable(string width, string style, string tableClass)
        {
            return CreateHTMLTable(width, style, tableClass, "0", "0", "0");
        }

        public HtmlTable CreateHTMLTable(string width, string style, string tableClass, string tableBorderWidth, string cellspacingValue, string cellpaddingValue)
        {
            HtmlTable ht = new HtmlTable();
            ht.Attributes.Add("width", width);
            ht.Attributes.Add("style", style);
            ht.Attributes.Add("class", tableClass);
            ht.Attributes.Add("border", tableBorderWidth);
            ht.Attributes.Add("cellspacing", cellspacingValue);
            ht.Attributes.Add("cellpadding", cellpaddingValue);

            return ht;
        }

        public HtmlGenericControl CreateHTMLMainTable(string width, string tableClass)
        {
            return CreateHTMLMainTable(width, string.Empty, tableClass, "0", "0", "0");
        }

        public HtmlGenericControl CreateHTMLMainTable(string width, string style, string tableClass)
        {
            return CreateHTMLMainTable(width, style, tableClass, "0", "0", "0");
        }

        public HtmlGenericControl CreateHTMLMainTable(string width, string style, string tableClass, string tableBorderWidth, string cellspacingValue, string cellpaddingValue)
        {
            HtmlGenericControl ht = new HtmlGenericControl("table");
            ht.Attributes.Add("width", width);
            ht.Attributes.Add("style", style);
            ht.Attributes.Add("class", tableClass);
            ht.Attributes.Add("border", tableBorderWidth);
            ht.Attributes.Add("cellspacing", cellspacingValue);
            ht.Attributes.Add("cellpadding", cellpaddingValue);

            return ht;
        }

        #endregion 创建表格
    }
}